using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using ORS.OrderRobot.ServiceContracts;
using ORS.OrderRobot.ServiceContracts.Dtos;

namespace ORS.OrderRobot.WebApp.Controllers
{
    /// <summary>
    /// 认证控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class AuthController : ControllerBase
    {
        private readonly IAdminService _adminService;

        public AuthController(IAdminService adminService)
        {
            _adminService = adminService;
        }

        /// <summary>
        /// 管理员登录
        /// </summary>
        /// <param name="request">登录请求</param>
        /// <returns>登录结果</returns>
        [HttpPost("login")]
        public async Task<ActionResult<AdminLoginResult>> Login([FromBody] AdminLoginRequest request)
        {
            if (string.IsNullOrEmpty(request.Username) || string.IsNullOrEmpty(request.Password))
            {
                return BadRequest(new { message = "用户名和密码不能为空" });
            }

            var result = await _adminService.LoginAsync(request.Username, request.Password);
            
            if (!result.Success)
            {
                return Unauthorized(new { message = result.Message });
            }

            return Ok(result);
        }

        /// <summary>
        /// 创建管理员（需要管理员权限）
        /// </summary>
        /// <param name="request">创建请求</param>
        /// <returns>创建结果</returns>
        [HttpPost("create-admin")]
        [Authorize(Roles = "Admin")]
        public async Task<ActionResult<AdminCreateResult>> CreateAdmin([FromBody] AdminCreateRequest request)
        {
            if (string.IsNullOrEmpty(request.Username) || string.IsNullOrEmpty(request.Password))
            {
                return BadRequest(new { message = "用户名和密码不能为空" });
            }

            var result = await _adminService.CreateAdminAsync(request.Username, request.Password, request.Role);
            
            if (!result.Success)
            {
                return BadRequest(new { message = result.Message });
            }

            return Ok(result);
        }

        /// <summary>
        /// 获取当前用户信息
        /// </summary>
        /// <returns>用户信息</returns>
        [HttpGet("profile")]
        [Authorize]
        public async Task<ActionResult<AdminDto>> GetProfile()
        {
            var userIdClaim = User.FindFirst("UserId");
            if (userIdClaim == null || !int.TryParse(userIdClaim.Value, out int userId))
            {
                return Unauthorized(new { message = "无效的用户信息" });
            }

            var admin = await _adminService.GetAdminAsync(userId);
            if (admin == null)
            {
                return NotFound(new { message = "用户不存在" });
            }

            return Ok(admin);
        }

        /// <summary>
        /// 测试认证
        /// </summary>
        /// <returns>认证状态</returns>
        [HttpGet("test")]
        [Authorize]
        public ActionResult TestAuth()
        {
            var username = User.Identity?.Name;
            var role = User.FindFirst("Role")?.Value;
            
            return Ok(new 
            { 
                message = "认证成功", 
                username = username,
                role = role,
                claims = User.Claims.Select(c => new { c.Type, c.Value }).ToList()
            });
        }
    }
} 